<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Powerless < wzxaini9@gmail.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use think\Validate;
use think\Db;
use cmf\controller\HomeBaseController;
use app\user\model\UserModel;
use app\common\model\ShopUser;
use app\common\model\ShopUserToken;
class LoginController extends HomeBaseController
{

    /**
     * 登录
     */
    public function index()
    {
        $redirect = $this->request->post("redirect");
        if (empty($redirect)) {
            $redirect = $this->request->server('HTTP_REFERER');
        } else {
            $redirect = base64_decode($redirect);
        }
        session('login_http_referer', $redirect);
        if (cmf_is_user_login()) { //已经登录时直接跳到首页
            return redirect($this->request->root() . '/');
        } else {
            return $this->fetch(":login");
        }
    }

    /**
     * 登录验证提交
     */
    public function doLogin()
    {
        $objUsers = new ShopUser();
        $objUsersToken = new ShopUserToken();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!cmf_captcha_check($data['captcha'])) {
                $this->error('验证码错误');
            }
            $uname = $_POST['username'];
            $upwd = md5($_POST['password']);
            $login = $objUsers->where(array('mobile'=>$uname,'password'=>$upwd))->field('user_id as id,nickname')->find();
            if($login){
                session('user',$login);
                //登录成功状态后
                $user_id = $login['id'];

                $time = time();
                $rand = rand(100000, 999999);
                $str = "hmy" . $time . $rand;
                $token = md5($str);
                $create_time = time();
                $update_time = time();
                $arr = array('user_id'=>$user_id,'token'=>$token,'create_time'=>$create_time,'update_time'=>$update_time);
                $data = $objUsersToken->insert($arr);
                if(!$data) {
                    $this->error('单点登录失败');
                }
                $arr['token'] = $token;

                $this->redirect('/index.php?g=index&m=index&a=index&token='.$token);
            }else{
                $this->error('账号或密码错误,请重试');
            }
        } else {
            $this->error("请求错误");
        }
    }

    /**
     * 单点登陆
     */
    public function dandian(){
        $token = $_GET['token'];
        $objUserToken = new ShopUserToken();
        $data = $objUserToken->where(array('token' => $token))->order('id', 'desc')->find();
        if(isset($data['user_id']) && !empty($data['user_id'])){
            $users_model=M('Users');
            $where = array(
                'user_id' => $data['user_id'],
            );
            $result = $users_model->where($where)->find();
            $_SESSION["user"]=$result;
            //写入此次登录信息
            $data = array(
                'last_login_time' => date("Y-m-d H:i:s"),
                'last_login_ip' => get_client_ip(0,true),
            );
            $users_model->where(array('id'=>$result["id"]))->save($data);
            $redirect=empty($_SESSION['login_http_referer'])?__ROOT__."/":$_SESSION['login_http_referer'];
            $_SESSION['login_http_referer']="";
            $this->success("登录成功！", $redirect);
        }else{
            $this->error('登录失败，token不存在');
        }
    }

    /**
     * 找回密码
     */
    public function findPassword()
    {
        return $this->fetch('/find_password');
    }

    /**
     * 用户密码重置
     */
    public function passwordReset()
    {

        if ($this->request->isPost()) {
            $validate = new Validate([
                'captcha'           => 'require',
                'verification_code' => 'require',
                'password'          => 'require|min:6|max:32',
            ]);
            $validate->message([
                'verification_code.require' => '验证码不能为空',
                'password.require'          => '密码不能为空',
                'password.max'              => '密码不能超过32个字符',
                'password.min'              => '密码不能小于6个字符',
                'captcha.require'           => '验证码不能为空',
            ]);

            $data = $this->request->post();
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            if (!cmf_captcha_check($data['captcha'])) {
                $this->error('验证码错误');
            }
            $errMsg = cmf_check_verification_code($data['username'], $data['verification_code']);
            if (!empty($errMsg)) {
                $this->error($errMsg);
            }

            $userModel = new UserModel();
            if ($validate::is($data['username'], 'email')) {

                $log = $userModel->emailPasswordReset($data['username'], $data['password']);

            } else if (preg_match('/(^(13\d|15[^4\D]|17[013678]|18\d)\d{8})$/', $data['username'])) {
                $user['mobile'] = $data['username'];
                $log            = $userModel->mobilePasswordReset($data['username'], $data['password']);
            } else {
                $log = 2;
            }
            switch ($log) {
                case 0:
                    $this->success('密码重置成功', $this->request->root());
                    break;
                case 1:
                    $this->error("您的账户尚未注册");
                    break;
                case 2:
                    $this->error("您输入的账号格式错误");
                    break;
                default :
                    $this->error('未受理的请求');
            }

        } else {
            $this->error("请求错误");
        }
    }


}